package com.zhengqing.wxmp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhengqing.wxmp.entity.ManualWxAccount;
import com.zhengqing.wxmp.mapper.ManualWxAccountMapper;
import com.zhengqing.wxmp.service.IManualWxAccountService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p> 微信公众号-用户 服务实现类 </p>
 *
 * @author zhengqingya
 * @description
 * @date 2023/03/15 18:28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ManualWxAccountServiceImpl extends ServiceImpl<ManualWxAccountMapper, ManualWxAccount> implements IManualWxAccountService {


    @Override
    public void initWxAccount(ManualWxAccount manualWxAccount) {
        if (StringUtils.isBlank(manualWxAccount.getOpenId())){
            return;
        }
        ManualWxAccount valiteBean = baseMapper.selectOne(Wrappers.<ManualWxAccount>lambdaQuery().eq(ManualWxAccount::getOpenId, manualWxAccount.getOpenId()));
        if (valiteBean != null){
            return;
        }
        manualWxAccount.setRemainingTimes(1);
        baseMapper.insert(manualWxAccount);
    }

    @Override
    public Boolean deductAccount(String openId) {
        ManualWxAccount manualWxAccount = baseMapper.selectOne(Wrappers.<ManualWxAccount>lambdaQuery().eq(ManualWxAccount::getOpenId, openId));
        if (ObjectUtil.isNull(manualWxAccount)){
            return false;
        }
        if (manualWxAccount.getRemainingTimes() <= 0){
            return false;
        }
        manualWxAccount.setRemainingTimes(manualWxAccount.getRemainingTimes()-1);
        baseMapper.updateById(manualWxAccount);
        return true;
    }
}
